﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using RanbuOM.Common;

namespace RanbuOM.Serialization
{
    public class RanbuReader : BinaryReaderEx
    {
        public string Path { get; set; }

        public RanbuReader(string path, Endianness endianness = Endianness.LittleEndian, bool tracking = false)
            : base(File.OpenRead(path), Encoding.ASCII, endianness, tracking)
        {
            this.Path = path;
        }

        public RanbuReader(Stream stream, Endianness endianness = Endianness.LittleEndian, bool tracking = false)
            : base(stream, Encoding.ASCII, endianness, tracking)
        {
        }

        public T ReadDataFile<T>() where T : DataFileBase, new()
        {
            T result = (T)this.ReadDataType(typeof(T));
            result.Path = this.Path;
            return result;
        }

        private object ReadDataType(Type type)
        {
            object result = Activator.CreateInstance(type);
            ((DataTypeBase)result).ReadFrom(this, null);
            return result;
        }

        [Conditional("DEBUG")]
        public void AssertOffset(Offset32 offset)
        {
            if (offset.Value == 0) { return; }

            var expected = offset.Base + offset.Value;
            if (this.Position != expected)
            {
                throw new InvalidOperationException(
                    string.Format("Position verification failed. Expected: {0:X8} = {1:X8} + {2:X8}. Actual: {3:X8} = {1:X8} + {4:X8}.",
                    expected,
                    offset.Base,
                    offset.Value,
                    this.Position,
                    this.Position - offset.Base));
            }
        }

        public void ReadDataProperties(DataTypeBase target, string group)
        {
            foreach (var prop in target.GetType().GetProperties())
            {
                var attr = DataPropertyAttribute.GetAttributeOrNull(prop);
                if (attr == null) { continue; }
                if (attr.Group != group) { continue; }
                this.ReadDataProperty(target, prop, attr);
            }
        }

        public Offset32 ReadOffset32(DataTypeBase context)
        {
            var result = new Offset32();
            result.Base = context.Position;
            result.ReadFrom(this, null);
            return result;
        }

        private object ReadSingleObject(Type type)
        {
            object value = null;
            if (type == typeof(SByte)) { value = this.ReadI8(); }
            else if (type == typeof(Int16)) { value = this.ReadI16(); }
            else if (type == typeof(Int32)) { value = this.ReadI32(); }
            else if (type == typeof(Int64)) { value = this.ReadI64(); }
            else if (type == typeof(Byte)) { value = this.ReadU8(); }
            else if (type == typeof(UInt16)) { value = this.ReadU16(); }
            else if (type == typeof(UInt32)) { value = this.ReadU32(); }
            else if (type == typeof(UInt64)) { value = this.ReadU64(); }
            else if (type == typeof(Single)) { value = this.ReadR4(); }
            else if (type == typeof(Char)) { value = this.ReadChar(); }
            else if (typeof(DataTypeBase).IsAssignableFrom(type)) { value = this.ReadDataType(type); }
            return value;
        }

        private void ReadDataProperty(DataTypeBase target, PropertyInfo prop, DataPropertyAttribute attr)
        {
            var type = prop.PropertyType;
            if (type.IsEnum) { type = type.GetEnumUnderlyingType(); }
            
            object value = null;
            if (type == typeof(String))
            {
                value = attr.SizeConst == 0 
                    ? this.ReadCString() 
                    : this.ReadCharArrayString(attr.SizeConst);
            }
            else if (type.IsArray)
            {
                Type elemType = type.GetElementType();
                var size = attr.SizeConst;
                var array = Array.CreateInstance(elemType, size);
                for (int i = 0; i < size; i++)
                {
                    object elemValue = this.ReadSingleObject(elemType);
                    array.SetValue(elemValue, i);
                }

                value = array;
            }
            else
            {
                value = this.ReadSingleObject(type);
                if (value == null)
                {
                    throw new InvalidOperationException("Unsupported type: " + type);
                }

                if (type == typeof(Offset32))
                {
                    ((Offset32)value).Base = target.Position;
                }
            }

            prop.SetValue(target, value, null);
        }

        public T[] ReadCreateArray<T>(int count) where T : new()
        {
            var result = new T[count];
            for (int i = 0; i < count; i++)
            {
                result[i] = (T)this.ReadSingleObject(typeof(T));
            }

            return result;
        }

        public void ReadListItems<T>(IList<T> list, string group, IList<Offset32> offsets = null, bool assertOffset = false) where T : DataTypeBase
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (offsets != null)
                {
                    var offset = offsets[i];
                    if (offset.Value == 0) { continue; }
                    if (assertOffset) { this.AssertOffset(offset); }
                    if (this.Position != offset.Base + offset.Value)
                    {
                        this.Seek(offset.Base + offset.Value);
                    }
                }

                list[i].ReadFrom(this, group);
            }
        }

        public ObservableCollection<T> ReadCreateObservableCollection<T>(int count) where T : new()
        {
            var result = new ObservableCollection<T>();
            for (int i = 0; i < count; i++)
            {
                result.Add((T)this.ReadSingleObject(typeof(T)));
            }

            return result;
        }
    }
}
